package stack;

import array.Array;

/**
 * @author lynn
 * @date 18-12-5 下午7:10
 */
public class ArrayStack<E> implements Stack<E> {

    private Array<E> array;

    /**
     * 无参构造
     */
    public ArrayStack() {
        this.array = new Array<>();
    }

    /**
     * 有参构造
     *
     * @param capacity 容量大小
     */
    public ArrayStack(int capacity) {
        this.array = new Array<>(capacity);
    }

    /**
     * 获取栈大小
     *
     * @return
     */
    @Override
    public int getSize() {
        return this.array.getSize();
    }

    /**
     * 栈是否为空
     *
     * @return
     */
    @Override
    public boolean isEmpty() {
        return this.array.isEmpty();
    }

    /**
     * 获取容量大小
     *
     * @return
     */
    public int getCapacity() {
        return this.array.getCapacity();
    }


    /**
     * 向栈中添加一个元素
     *
     * @param e
     */
    @Override
    public void push(E e) {
        this.array.addLast(e);
    }

    /**
     * 获取栈顶元素，并将该元素移出栈
     *
     * @return
     */
    @Override
    public E pop() {
        return this.array.removeLast();
    }

    /**
     * 获取栈顶元素，不移除该元素
     *
     * @return
     */
    @Override
    public E peek() {
        return this.array.getLast();
    }


    /**
     * Returns a string representation of the object. In general, the
     * {@code toString} method returns a string that
     * "textually represents" this object. The result should
     * be a concise but informative representation that is easy for a
     * person to read.
     * It is recommended that all subclasses override this method.
     * <p>
     * The {@code toString} method for class {@code Object}
     * returns a string consisting of the name of the class of which the
     * object is an instance, the at-sign character `{@code @}', and
     * the unsigned hexadecimal representation of the hash code of the
     * object. In other words, this method returns a string equal to the
     * value of:
     * <blockquote>
     * <pre>
     * getClass().getName() + '@' + Integer.toHexString(hashCode())
     * </pre></blockquote>
     *
     * @return a string representation of the object.
     */
    @Override
    public String toString() {

        StringBuilder res = new StringBuilder();
        res.append("Stack: ");
        res.append('[');
        for (int i = 0; i < this.array.getSize(); i++) {
            res.append(this.array.get(i));
            if (i != this.array.getSize() - 1) {
                res.append(", ");
            }
        }
        res.append("] top ");

        return res.toString();
    }
}
